package com.easykoo.web.tag;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
import java.io.IOException;

public class CountTag extends TagSupport {

    private String foundMessage;
    private String notFoundMessage;

    private JspWriter out;

    public int doStartTag() throws JspException {

        FormTag formTag = (FormTag) getParent();
        PageInfo pageInfo = formTag.getPageInfo();
        if (pageInfo != null) {
            StringBuffer body = new StringBuffer("");
            body.append("<span ");
            if (pageInfo.getResult() != null && pageInfo.getResult().size() != 0) {
                body.append(">");
                body.append(foundMessage.replace("@count", pageInfo.getTotalFound() + ""));
            } else {
                body.append("style=\"color:red;\"");
                body.append(">");
                body.append(notFoundMessage);
            }
            body.append("</span>");
            out = this.pageContext.getOut();
            try {
                out.write(body.toString());
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    out.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return SKIP_BODY;
    }

    public String getFoundMessage() {
        return foundMessage;
    }

    public void setFoundMessage(String foundMessage) {
        if (BaseTag.isNotBlank(foundMessage)) {
            this.foundMessage = foundMessage;
        } else {
            this.foundMessage = PageInfo.TOTAL_FOUND;
        }
    }

    public String getNotFoundMessage() {
        return notFoundMessage;
    }

    public void setNotFoundMessage(String notFoundMessage) {
        if (BaseTag.isNotBlank(notFoundMessage)) {
            this.notFoundMessage = notFoundMessage;
        } else {
            this.notFoundMessage = PageInfo.NOT_FOUND;
        }
    }
}